<?php
/**
 * 发送验证码
 */

$json = array('status' => 'error', 'msg' => 'error', 'data' => []);

$phone = fn_post('phone');
$tp = fn_post('tp', '0');
$configura = fn_configura($this->website, 'app');
$time = $_SERVER['REQUEST_TIME'];

if (!preg_match('/^1\d{10}/', $phone)) {
	$json['msg'] = '请输入正确的手机号码!';
	$this->json_encode_encrypt($json);exit();
}

switch ($tp) {
case '1': //登录-判断手机号码是否存在
	break;
case '2': //找回密码
	break;
case '0': //注册
default:
	if ($tp == 0 && $this->website['class']['db']
		->table('user')
		->where('phone=?', $phone)
		->limit(1)
		->count()) {
		$json['msg'] = '手机号码已被注册!';
		$this->json_encode_encrypt($json);exit();
	}
}

if ($this->website['class']['db']
	->table('user_code')
	->where('ip = ? and tp=? and createtime between ? and ?', fn_ip_long(), $tp, $time - $configura['verificationhour'] * 3600, $time)
	->count() > ($configura['verificationip'] - 1)) {
	$json['msg'] = '抱歉，您在发送的验证码有点多了!';
} elseif ($this->website['class']['db']
		->table('user_code')
		->where('phone = ? and tp=? and createtime between ? and ?', $phone, $tp, $time - $configura['verificationhour'] * 3600, $time)
		->count() > ($configura['verificationnum'] - 1)) {
	$json['msg'] = '抱歉，您发送的验证码有点多了!';
} else {

	$code = $this->website['class']['db']
		->table('user_code')
		->field('createtime')
		->where('phone=? and tp=? and createtime>?', $phone, $tp, $time - $configura['verificationseconds'])
		->one();

	if ($code['createtime'] ?? false) {
		$seconds = $configura['verificationseconds'] - ($time - $code['createtime']);
		$json['msg'] = '验证码已发送过，请您' . $seconds . '秒后重试.';
		$json['data']['seconds'] = $seconds;
	} else {
		$code = '1';
		$max = ($configura['verificationdigit'] ?? 1) - 1;
		for ($num = 0; $num < $max; $num++) {
			$code .= rand(0, 9);
		}
		// $code = str_pad($code, $configura['verificationdigit'], rand(0, 9), STR_PAD_BOTH);

		$id = $this->website['class']['db']
			->table('user_code')
			->field('phone', 'code', 'tp', 'ip', 'createtime')
			->value($phone, $code, $tp, fn_ip_long(), $time)
			->insert();
		$json['sql'] = $this->website['class']['db']->sql;
		if ($id) {
			$json['status'] = 'ok';
			if (!$configura['verification']) {
				$json['msg'] = '验证码：' . $code;
			} else {
				fn_sms_code($tp, $phone, $code);
				$json['msg'] = '验证码已发送,注意查收';
			}
		} else {
			$json['msg'] = '验证码保存错误!';
		}
	}

}

$this->json_encode_encrypt($json);